"""
测试运行脚本
自动运行所有单元测试并生成覆盖率报告
"""

import unittest
import coverage
import os
import sys
from pathlib import Path

def run_tests():
    """运行所有测试并生成报告"""
    # 初始化覆盖率分析
    cov = coverage.Coverage(
        source=['src'],
        omit=['*/__init__.py', '*/main.py']
    )
    cov.start()
    
    # 自动发现并运行测试
    test_dir = Path(__file__).parent / 'tests'
    test_loader = unittest.TestLoader()
    test_suite = test_loader.discover(str(test_dir), pattern='test_*.py')
    
    test_runner = unittest.TextTestRunner(verbosity=2)
    result = test_runner.run(test_suite)
    
    # 生成覆盖率报告
    cov.stop()
    cov.save()
    
    print("\n" + "="*50)
    print("测试覆盖率报告:")
    cov.report()
    
    # 生成HTML报告
    cov.html_report(directory='htmlcov')
    print("\nHTML报告已生成到htmlcov目录")
    
    # 返回测试结果
    return result.wasSuccessful()

if __name__ == '__main__':
    # 确保Python可以找到src模块
    sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
    
    success = run_tests()
    sys.exit(0 if success else 1)